package com.zf.shuashua.net;

import android.content.Context;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zf.shuashua.api.Store;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import java.net.Proxy;
import java.util.concurrent.TimeUnit;

public class RetrofitUtil {

    private static RetrofitUtil mHttpMethods = null;

    private Retrofit mRetrofit;

    public static Context mContext;

    /**
     * 私有构造器
     */
    private RetrofitUtil() {
        //网络框架
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .addInterceptor(new LoggerIntercepter("RetrofitUtil"))
                .addInterceptor(new MyHeaderIntercepter(mContext))
                .addInterceptor(new ReceivedCookiesInterceptor(mContext))
                .addInterceptor(new AddCookiesInterceptor(mContext));

        if(!Store.getInstance().isProxy()){
            builder.proxy(Proxy.NO_PROXY);
        }
        Gson gson = new GsonBuilder().setLenient().create();
        mRetrofit = new Retrofit.Builder()
                .client(builder.build())
                .baseUrl(ApiConstant.baseUrl)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    public static RetrofitUtil getInstance() {
        if (mHttpMethods == null) {
            synchronized (RetrofitUtil.class) {
                if (mHttpMethods == null) {
                    mHttpMethods = new RetrofitUtil();
                }
            }
        }
        return mHttpMethods;
    }

    public <T> T getApiService(final Class<T> service) {
        return mRetrofit.create(service);
    }


}
